<?php

namespace App\Http\Controllers\Income;

use App\Http\Controllers\Controller;
use App\Http\Controllers\HelperController;
use App\Imports\Income\IncomeCashImport;
use App\Models\Bus\BusDistribution;
use App\Models\Income\IncomeCash;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;

class IncomeCashController extends Controller
{
    public function incomeCashList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);

        $data = $this->getIncomeCashList($params)
            ->orderByDesc('date')
            ->orderBy('license_plate_num')
            ->get()->toArray();
        $dataCount = $this->getIncomeCashList($countParams)->count();

        return response()->formatJson(['cashRecord' => $data, 'count' => $dataCount]);
    }

    public function getIncomeCashList($params): \Illuminate\Database\Eloquent\Builder
    {
        $query = IncomeCash::query();

        if (isset($params['license_plate_num'])) {
            $query->where('license_plate_num', 'like', '%'.$params['license_plate_num'].'%');
        }

        if ($params['date'][0] !== null && $params['date'][1] !== null) {
            $startDate = date('Y-m-d', strtotime($params['date'][0]));
            $endDate = date('Y-m-d', strtotime($params['date'][1]));
            $query->whereBetween('date', [$startDate, $endDate]);
        }

        if (isset($params['pageNumber'], $params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query;
    }

    /**
     * 创建车辆信息
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function storeCash(Request $request)
    {
        $params = $request->all();
        if ($params['license_plate_num']) {
            $params['license_plate_num'] = Str::of($params['license_plate_num'])->replace('陕G', '');
        }
        $cash = new IncomeCash($params);
        $result = $cash->save();
        $message = $result ? '添加成功' : '添加失败';

        return response()->formatJson($result, $message);
    }

    /**
     * 修改文章
     *
     * @param  Request  $request
     * @param           $id
     *
     * @return mixed
     */
    public function updateCash(Request $request, $id)
    {
        $params = $request->all();
        if ($params['license_plate_num']) {
            $params['license_plate_num'] = Str::of($params['license_plate_num'])->replace('陕G', '');
        }
        $cash = IncomeCash::query()->find($id);

        $result = $cash->update($params);

        $message = $result ? '修改成功' : '修改失败';

        return response()->formatJson($result, $message);
    }

    /**
     * 删除车辆信息
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function destroyCash(Request $request)
    {
        $result = false;
        if ($request->has('ids')) {
            $ids = explode(',', $request['ids']);
            $cashCount = IncomeCash::destroy($ids);
            $result = $cashCount !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }

    /**
     * 导入现金收入
     *
     * @param  Request  $request
     *
     * @return mixed
     * @throws \Exception
     */
    public function importCash(Request $request)
    {
        $urlParse = parse_url($request->input('url'));
        $excelData = Excel::toArray(new IncomeCashImport, public_path().$urlParse['path']);
        $fullData = $excelData[0];
        //新加标志参数用来二次确认是否导入数据 值为true或者false
        $mark = $request->input('mark');
        array_shift($fullData);

        $data = [];
        $fields = [
            'date',
            'license_plate_num',
            'cash_income',
        ];
        $busNumberArray = BusDistribution::query()
            ->orderBy('license_plate_num')
            ->groupBy('license_plate_num')
            ->pluck('license_plate_num')
            ->toArray();
        // 整理数据，填充合并的单元格数据
        foreach ($fullData as $row) {
            if (! $row[0]) {
                continue;
            }
            $item = [];
            foreach ($fields as $index => $field) {
                $item[$field] = $row[$index];
            }
            if ($item['license_plate_num']) {
                $item['license_plate_num'] = Str::of($item['license_plate_num'])->replace('陕G', '');
            }
            $date = $item['date'] = HelperController::transformDateTime($item['date']);
            if (!$mark) {
                // 检测数据是否重复
                $count = IncomeCash::query()->where('date',$date)->count();
                if ($count) {
                    return response()->formatJson('', $date.'数据已存在，是否继续导入?');
                }
                //检测车牌号
                $msg = $this->checkBusNumber($item['license_plate_num'],$busNumberArray);
                if ($msg) {
                    return response()->formatJson('', $msg);
                }
            }
            $item['created_at'] = date('Y-m-d H:i:s');
            $data[] = $item;
        }
        if ($mark) {
            IncomeCash::query()->where('date', $date)->delete();
        }
        $result = IncomeCash::query()->insert($data);


        return response()->formatJson($result, '导入成功');
    }

    public function checkBusNumber($licensePlateNum, $busNumberArray)
    {
        $licensePlateNum = trim($licensePlateNum);
        $licensePlateNum = str_replace('陕G', '', $licensePlateNum);
        $msg = [];
        //车牌号不能为空
        if (! $licensePlateNum) {
            $msg[] = '车牌号不能为空!';
        }
        //检测车牌号是否在线路分布图中
        if (! in_array($licensePlateNum, $busNumberArray)) {
            $msg[] = '车牌号'.$licensePlateNum.'不存在!';
        }
        return $msg;
    }
}
